

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class RegServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//验证完毕及其之后的存储

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		String email=request.getParameter("email");
		String user=request.getParameter("user");
		String pwd= request.getParameter("pwd");
		String vali1=request.getParameter("vali");
		String errMsg="";
		String vali=request.getSession().getAttribute("vali").toString();
		if(vali==""||vali==null)
			errMsg+="验证码为空";
		//首先验证验证码正确不，不正确就提示
		if(vali.equals(vali1)) {
			//服务端的验证
			String ageStr = request.getParameter("age");
			int age = 0;
			if (ageStr != null) {
				age = Integer.parseInt(ageStr);
			} else {
				errMsg += "年龄不能为空!";
			}
			//说明服务端验证里面有错误，打印错误
			if (errMsg != "" || errMsg.length() > 0) {
				out.println(errMsg);
			} else {
				out.println("恭喜你，注册成功，请牢记你的邮箱：" + email + "你的密码是：" + pwd + "你的年龄：" + age +"你的用户名："+user);
				//todo:放到数据库Mysql
                MemberService memberService=new MemberService();
				Member member=MemberDao.login(user,pwd);
               // if(!memberService.login(user.getBytes(),pwd.getBytes()))
				BufferedWriter bw = null;
				try {

					bw = new BufferedWriter(new FileWriter("D:\\ApacheTomcat\\apache-tomcat-9.0.33\\webclass\\web\\info.txt", true));
//					把相关内容写到对应地址下的文本文件当中
					//应该改为写到数据库之中
					bw.write("邮箱：" + email + "\t密码：" + pwd + "\t用户:" + user);
					bw.newLine();
					bw.close();
				} catch (IOException e) {
					throw new RuntimeException("存储数据失败" + e.getMessage());
				} finally {
					if (bw != null) {
						try {
							bw.close();
						} catch (IOException e) {
							throw new RuntimeException("关闭文件失败" + e.getMessage());
						}
					}
				}
			}
		}
		else
		{
			out.println("验证码错误！");
		}
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}
